<template>
  <a class="community-item">
    <div class="item-center">
      <div class="text">{{title}}</div>
    </div>
  </a>
</template>
<script setup>
  import { ref, watch, onMounted, nextTick } from "vue";

  const props = defineProps({
    title: {
      type: String,
      default: '环河社区社区社区社区'
    }
  });
  const setupScroll = (el) => {
    const container = el.querySelector(".item-center");
    const textEl = container?.querySelector(".text");

    if (!container || !textEl) return;

    const containerWidth = container.clientWidth;
    const textWidth = textEl.scrollWidth;

    if (textWidth <= containerWidth) return; // 不需要滚动

    const offset = textWidth - containerWidth;
    let loopTimer = null;

    const scrollOnce = () => {
      // 滚动到最后一个字
      textEl.style.transition = "transform 4s linear";
      textEl.style.transform = `translateX(-${offset}px)`;

      setTimeout(() => {
        // 平滑回到起点
        textEl.style.transition = "transform 1s ease-in-out";
        textEl.style.transform = "translateX(0px)";
      }, 4000);
    };

    const startLoop = () => {
      scrollOnce();
      loopTimer = setInterval(scrollOnce, 5100); // 总周期：4s + 1s + 少量延迟
    };

    const stopLoop = () => {
      if (loopTimer) clearInterval(loopTimer);
      loopTimer = null;
      // 强制回滚，避免卡在中间状态
      textEl.style.transition = "transform 1s ease-in-out";
      textEl.style.transform = "translateX(0px)";
    };

    // 事件绑定
    el.addEventListener("mouseenter", () => {
      if (!loopTimer) {
        startLoop();
      }
    });

    el.addEventListener("mouseleave", () => {
      stopLoop();
    });
  };

  onMounted(() => {
    nextTick(() => { 
      document.querySelectorAll(".community-item").forEach(setupScroll);
    });
  });
</script>
<style lang="scss" scoped>
.community-item {
    width: 156px;
    height: 47px;
    overflow: hidden;
    white-space: nowrap;
    background: url("@/assets/images/community1.png") no-repeat;
    background-size: 100% 100%;
    display: flex;
    align-items: center;
    justify-content: center;
    
    cursor: pointer;
  
    
    &:hover { 
      background: url("@/assets/images/community2.png") no-repeat;
      .text{
        color: #fff;
      }
    }
    .item-center {
      position: relative;
      width: 126px; /* 固定容器宽度 */
      overflow: hidden; /* 隐藏超出内容 */
      height: 47px;
      display: flex;
      align-items: center;
      justify-content: center;
    }

    .text {
      position: absolute;
      white-space: nowrap;
      font-weight: 500;
      font-size: 18px;
      color: #aa7b3b;
      &.resetting {
        animation: resetScroll 1.5s ease-in-out forwards;
      }
    }
    .community-item:hover .text {
      animation-play-state: running; /* 悬停时播放动画 */
    }
  }
</style>